﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using Utils;
using BLL;
/*
 * 设定角色的菜单组
 * 每个部门有一个根据部门属性设定的默认角色，自动生成帐号的时候，帐号根据部门属性对应一个默认角色限定的菜单
 * 系统人员还可以定义自己的角色，供帐号使用
 * 
 * 
 * 
 * 
 */


namespace UI.ModSystem
{
    public partial class SetSysRoleMenu : System.Web.UI.Page
    {

        //MenuBiz menuBiz = new MenuBiz();
        IBizSQL bizSQL = new BizSQL();
        string strAimTable = "Sys_SysRoleMenu";
        //存储该帐号菜单的所有ID,在生成菜单树的时候，让已经具有的显示选中状态
        private ArrayList alAccountID = new ArrayList();
        string sysRoleID = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["SysRoleID"] != null)
            {
                sysRoleID = Request.Params["SysRoleID"].ToString();              
            }
            else
            {
                JSUtility.Alert(this,"参数错误");
                return;
            }

            
            if (!IsPostBack)
            {loadOldMenu(sysRoleID);
                lbRole.Text = "为角色设定菜单" + sysRoleID;
            }
        }
        //设定系统角色菜单
        protected void btnConfigMenu_Click(object sender, EventArgs e)
        {
            string strSysRoleID = sysRoleID;
            try
            {
                //插入选定的菜单
                InsertAllSelectNodeID(MainMenuTreeView.Nodes, strSysRoleID);
                //Response.Redirect("SetSysRoleMenu.aspx?SysRoleID=" + strSysRoleID);
                Response.Write("<script>window.alert('设定系统角色的菜单成功！')</script>");
            }
            catch (Exception ex)
            {
                Response.Write("错误，错误原因：" + ex.Message);
                Response.End();
            }
        }
        ////设定自定义角色菜单
        //protected void btnSelfSet_Click(object sender, EventArgs e)
        //{
        //    string strSysRoleID = ddlSelfRole.SelectedValue.Trim();
        //    try
        //    {
        //        //插入选定的菜单
        //        InsertAllSelectNodeID(MainMenuTreeView.Nodes, strSysRoleID);
        //        //Response.Redirect("SetSysRoleMenu.aspx?SysRoleID=" + strSysRoleID);
        //        Response.Write("<script>window.alert('设定自定义角色的菜单成功！')</script>");
        //    }
        //    catch (Exception ex)
        //    {
        //        Response.Write("错误，错误原因：" + ex.Message);
        //        Response.End();
        //    }

        //}
        protected void InsertAllSelectNodeID(TreeNodeCollection tnc, string strSysRoleID)
        {
            foreach (TreeNode node in tnc)
            {
                //string strInsertSQL = "INSERT INTO Sys_AccountMenu (AccountID,MainMenuID) VALUES (" + iAccountID + "," + Int32.Parse(node.Value.ToString()) + ")";
                //插入数据
                if (node.Checked)//如果选中了此菜单
                {
                    if (bizSQL.ExecSQL2("SELECT * FROM Sys_SysRoleMenu WHERE SysRoleID='" + strSysRoleID + "' AND MainMenuID = " + Int32.Parse(node.Value.ToString())).Tables[0].Rows.Count <= 0)//该条记录不存在
                    {
                        //INSERT INTO "表格名" ("栏位1", "栏位2", ...) VALUES ("值1", "值2", ...)  插入数据
                        bizSQL.ExecSQL("INSERT INTO Sys_SysRoleMenu (SysRoleID,MainMenuID) VALUES ('" + strSysRoleID + "'," + Int32.Parse(node.Value.ToString()) + ")");
                    }
                }
                else ////如果没有选中此菜单
                {
                    bizSQL.ExecSQL("DELETE FROM Sys_SysRoleMenu WHERE SysRoleID='" + strSysRoleID + "' AND MainMenuID = " + Int32.Parse(node.Value.ToString()));
                }
                if (node.ChildNodes.Count != 0)
                    InsertAllSelectNodeID(node.ChildNodes, strSysRoleID);
            }
        }
        //protected void DDListDepartmentPropertie_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    loadOldMenu(DDListDepartmentPropertie.SelectedValue);
        //}

        //protected void ddlSelfRole_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    loadOldMenu(ddlSelfRole.SelectedValue);
        //}

        protected void loadOldMenu(string strSysRoleID)
        {

            string strDeleteSQL = "DELETE FROM " + strAimTable;
            strDeleteSQL += " WHERE SysRoleID='" + strSysRoleID + "' AND MainMenuID NOT IN (SELECT MainMenuID FROM Sys_MainMenu WHERE State='Y')";
            bizSQL.ExecSQL(strDeleteSQL);
            //取出该帐号定义过的菜单ID（上面把不存在的已经删除）并填充到ArrayList alAccountID
            //alAccountID是用来实现该帐号的菜单在显示的时候选中
            DataTable dtMainMenuID = bizSQL.ExecSQL2("SELECT MainMenuID from " + strAimTable + " WHERE SysRoleID='" + strSysRoleID + "'").Tables[0];
            int count = dtMainMenuID.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                alAccountID.Add(dtMainMenuID.Rows[i]["MainMenuID"].ToString());
            }
            Create_MainMenu_TreeView();
            this.MainMenuTreeView.Attributes.Add("onclick", "CheckEvent()");
        }

        private void Create_MainMenu_TreeView()
        {
            MainMenuTreeView.Nodes.Clear();
            //取出菜单数据
            string strSQL = "select MainMenuID,ParentID,MenuName from Sys_MainMenu order by AbsIndex DESC";
            DataSet ds = bizSQL.ExecSQL2(strSQL);
            if (ds == null)
            {
                return;
            }
            else
            {
                this.ViewState["ds"] = ds;

                //调用递归函数，完成树形结构的生成
                AddTree(0, (TreeNode)null);
            }
        }
        //递归添加树的节点
        private void AddTree(int ParentID, TreeNode pNode)
        {
            DataSet ds = (DataSet)this.ViewState["ds"];
            DataView dvTree = new DataView(ds.Tables[0]);
            //过滤ParentID,得到当前的所有子节点
            dvTree.RowFilter = "[ParentID] = " + ParentID;

            foreach (DataRowView Row in dvTree)
            {
                TreeNode Node = new TreeNode();

                if (pNode == null)
                {    //添加根节点

                    Node.Text = Row["MenuName"].ToString();
                    Node.Value = Row["MainMenuID"].ToString();
                    MainMenuTreeView.Nodes.Add(Node);
                    //if (alAccountID.Contains(Row["MainMenuID"].ToString()))
                    if (alAccountID.IndexOf(Row["MainMenuID"].ToString()) != -1)
                    {
                        Node.Checked = true;
                    }
                    //Node.Expanded = true;
                    AddTree(Int32.Parse(Row["MainMenuID"].ToString()), Node);    //再次递归
                }
                else
                {   //̀添加当前节点的子节点
                    Node.Text = Row["MenuName"].ToString();
                    Node.Value = Row["MainMenuID"].ToString();
                    pNode.ChildNodes.Add(Node);
                    //if (alAccountID.Contains(Row["MainMenuID"].ToString()))
                    if (alAccountID.IndexOf(Row["MainMenuID"].ToString()) != -1)
                    {
                        Node.Checked = true;
                    }
                    //Node.Expanded = true;
                    AddTree(Int32.Parse(Row["MainMenuID"].ToString()), Node);     //再次递归
                }
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("DefineSysRole.aspx");
        }


        //
    }
}
